package com.example.zhu.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhu.config.JwtProperties;
import com.example.zhu.entity.Admin;
import com.example.zhu.result.Result;
import com.example.zhu.mapper.AdminMapper;
import com.example.zhu.service.LoginService;
import com.example.zhu.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl extends ServiceImpl<AdminMapper, Admin> implements LoginService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public Result login(Admin admin) {
        Admin admin1 = adminMapper.selectById(admin.getUsername());
        if(admin1==null){
            return Result.error("账号不存在");
        }
        String md5password = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        if(!admin1.getPassword().equals(md5password)){
            return Result.error("密码错误");
        }
        Map map=new HashMap<>();
        map.put("username",admin.getUsername());
        //创建jwt令牌
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                map);
        return Result.success(token);
    }

    @Override
    public Result Register(Admin admin) {
        Admin admin1 = adminMapper.selectById(admin.getUsername());
        if(admin1!=null){
            return Result.error("账号已存在");
        }
        String md5password = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        admin.setPassword(md5password);
        admin.setType("0");
        adminMapper.insert(admin);
        return Result.success(null);
    }
}
